<?php
namespace App\Api\Controllers\Zgyd;

use App\Api\Controllers\zgyd\BaseController as base;
use Illuminate\Support\Facades\DB;

class PayController extends BaseController
{
    public function __construct()
    {

    }


    public function scan_pay($data)
    {
        try {
            if ($data['ways_source'] == 'weixin') {
                $TranId = '201002';
                $PayType = 'WEIX';
            }
            if ($data['ways_source'] == 'alipay') {
                $TranId = '201001';
                $PayType = 'ZFBA';
            }
            if ($data['ways_source'] == 'unionpay') {
                return [
                    'status' => 3,
                    'message' => '暂不支付云闪付!',
                ];
            }

            $txnAmt = substr( strval($data['total_amount'] * 100 + 1000000000000), 1, 15 ); // 交易金额（分，12 位，不足左补 0）

            $params = [
                "TranId" => $TranId,
                "BussId" => $data['sales_no'],

                "BatchNo" => substr(date('Ymd'), 2),
                "PayType" => $PayType,
                "AuthCode" => $data['code'],
                "TranAmt" => $txnAmt,
                "CcyCode" => "156",
                "Body" => "scan",
                "priKey" => $data['pri_key'],
                "SignParams" => [
                    "MerId" => $data['mch_id'],
                    "TermId" => $data['pos_no'],
                    "PayLs" =>  $data['out_trade_no'],
                    "TraceNo" => (string)rand(100000, 999999)
                ]
            ];




//            if (isset($data['body']) && !empty($data['body'])) {
//                $params['txnOrderBody'] = $data['body'];
//            }

            $base = base::getInstance();
            $ret  = $base->params($params)->build('scan_pay', $base::SCAN_URL);

            if (isset($ret['RespCode']) && !empty($ret['RespCode'])) {
                if ($ret['RespCode'] == "000000") { //支付成功
                    return [
                        'status' => 1,
                        'message' => '支付成功',
                        'data' => $ret
                    ];
                } else if ($ret['RespCode'] == '888888' || $ret['RespCode'] == '999999') {
                    return [
                        'status' => 2,
                        'message' => '支付中',
                    ];
                } else {
                    $message = '失败了';
                    if (isset($ret['RespMsg'])) {
                        $message = $ret['RespMsg'];
                    }
                    return [
                        'status' => 3,
                        'message' => $message,
                    ];
                }
            } else {
                return [
                    'status' => 3,
                    'message' => '支付异常',
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => 3,
                'message' => $ex->getMessage().' | '.$ex->getLine(),
            ];
        }
    }


    //查询订单 0-系统错误 1-成功 2-正在支付 3-失败 4.已经退款
    public function order_query($data)
    {
        try {
            if ($data['ways_source'] == 'weixin') {
                $TranId = '201002';
                $PayType = 'WEIX';
            }
            if ($data['ways_source'] == 'alipay') {
                $TranId = '201001';
                $PayType = 'ZFBA';
            }
            if ($data['ways_source'] == 'unionpay') {
                return [
                    'status' => 3,
                    'message' => '暂不支付云闪付!',
                ];
            }
            $txnAmt = substr( strval($data['total_amount'] * 100 + 1000000000000), 1, 15 ); // 交易金额（分，12 位，不足左补 0）

            $params = [
                "TranId" => '201006',
                "BussId" => $data['sales_no'],

                "BatchNo" => substr(date('Ymd'), 2),
                "priKey" => $data['pri_key'],
                "OldPayType" => $PayType,
                'OldTranId' => $TranId,
                "OldPayLs" =>  $data['out_trade_no'],
                "OldTranAmt" =>  $txnAmt,
                "OldCcyCode" =>  '156',
                "SignParams" => [
                    "MerId" => $data['mch_id'],
                    "TermId" => $data['pos_no'],
                    "PayLs" =>  $data['out_trade_no'],
                    "TraceNo" => (string)rand(100000, 999999)
                ]
            ];
            $base = base::getInstance();

            $url = $base::SCAN_URL;
//            if (DB::table('orders')->where(['out_trade_no' => $data['out_trade_no']])->value('pay_method') == 'qr_code') {
//                $url = $base::QR_URL;
//                $params = [
//                    "BussId" => $data['sales_no'],
//                    "BatchNo" => substr(date('Ymd'), 2),
//                    "priKey" => $data['pri_key'],
//                    'OldTranId' => $TranId,
//                    "QrCode" =>  $data['out_trade_no'],
//                    "OldTranAmt" =>  $txnAmt,
//                    "OldCcyCode" =>  '156',
//                    "SignParams" => [
//                        "MerId" => $data['mch_id'],
//                        "TermId" => $data['pos_no'],
//                        "PayLs" =>  $data['out_trade_no'],
//                        "TranId" => '203003',
//                    ]
//                ];
//            }
            $ret  = $base->params($params)->build('order_query', $url);

            if (isset($ret['RespCode']) && !empty($ret['RespCode'])) {
                if ($ret['OldRespCode'] == "000000") { //支付成功
                    return [
                        'status' => 1,
                        'message' => '支付成功',
                        'data' => $ret
                    ];
                } else if ($ret['OldRespCode'] == '888888' || $ret['OldRespCode'] == '999999') {
                    return [
                        'status' => 2,
                        'message' => '支付中',
                    ];
                } else {
                    $message = '失败了';
                    if (isset($ret['OldRespMsg'])) {
                        $message = $ret['OldRespMsg'];
                    }
                    return [
                        'status' => 3,
                        'message' => $message,
                    ];
                }
            } else {
                $message = '支付异常';
                if (isset($ret['ErrorMsg'])) {
                    $message = $ret['ErrorMsg'];
                }
                return [
                    'status' => 3,
                    'message' => $message,
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => '0',
                'message' => $ex->getMessage().' | '.$ex->getLine(),
            ];
        }
    }


    //退款 0-系统错误 1-成功
    public function refund($data)
    {
        try {
//            $params = [
//                'posNo' => $data['pos_no'],
//                'key' => $data['key'],
//                'tranType' => 'R',
//                'mid' => $data['mch_id'],
//                'vfTradeNo' => $data['refund_no'],
//                'merTradeNo' => $data['out_trade_no'],
//                'txnAmt' => (string)($data['refund_amount'] * 100),
//                'tid' => $data['pos_no'],
//            ];

            if ($data['ways_source'] == 'weixin') {
                $TranId = '201002';
                $PayType = 'WEIX';
            }
            if ($data['ways_source'] == 'alipay') {
                $TranId = '201001';
                $PayType = 'ZFBA';
            }
            if ($data['ways_source'] == 'unionpay') {
                return [
                    'status' => 3,
                    'message' => '暂不支付云闪付!',
                ];
            }

            $txnAmt = substr( strval($data['refund_amount'] * 100 + 1000000000000), 1, 15 ); // 交易金额（分，12 位，不足左补 0）

            $params = [
                "TranId" => '201005',
                "BussId" => $data['sales_no'],

                "BatchNo" => substr(date('Ymd'), 2),
                "priKey" => $data['pri_key'],
                "OldPayType" => $PayType,
                'OldTranId' => $TranId,
                "OldPayLs" =>  $data['out_trade_no'],
                "RefundAmt" =>  $txnAmt,
                "OldBankDate" =>   date('Ymd', strtotime($data['pay_time'])),
                "OldOrderNo" =>  $data['user_bar_code'],
                "SignParams" => [
                    "MerId" => $data['mch_id'],
                    "TermId" => $data['pos_no'],
                    "PayLs" =>  $data['refund_no'],
                    "TraceNo" => (string)rand(100000, 999999)
                ]
            ];


            $base = base::getInstance();

            $url = $base::SCAN_URL;
            if (strpos($data['out_trade_no'], "qr") !== false) {
                $url = $base::QR_URL;
            }

            $ret  = $base->params($params)->build( 'refund', $url);

            if (isset($ret['RespCode']) && !empty($ret['RespCode'])) {

                if ($ret['RespCode'] == '000000') {
                    return [
                        'status' => 1,
                        'message' => '退款成功',
                        'data' => [
                            'refund_count' => 1,
                            'out_trade_no'  => $data['out_trade_no'],
                        ]
                    ];
                } else {
                    $message = '失败了';
                    if (isset($ret['RespMsg'])) {
                        $message = $ret['RespMsg'];
                    }
                    return [
                        'status' => 2,
                        'message' => $message
                    ];
                }
            } else {
                $message = '支付异常';
                if (isset($ret['ErrorMsg'])) {
                    $message = $ret['ErrorMsg'];
                }
                return [
                    'status' => 2,
                    'message' => $message,
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getLine()
            ];
        }
    }


    //退款查询 0-系统错误 1-成功 2-正在退款 3-失败
    public function refund_query($data)
    {
        try {


        } catch (\Exception $ex) {
            return [
                'status' => '0',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }

    public function qr_submit($data)
    {
        try {


            $txnAmt = substr( strval($data['total_amount'] * 100 + 1000000000000), 1, 15 ); // 交易金额（分，12 位，不足左补 0）

            $params = [

                "BussId" => $data['sales_no'],
                "BatchNo" => substr(date('Ymd'), 2),
                "DeviceType" => '11',
                "TranAmt" => $txnAmt,
                "priKey" => $data['pri_key'],
                'NotifyUrl' =>  url('/api/zgyd/pay_notify_url'),
                "SignParams" => [
                    "MerId" => $data['mch_id'],
                    "TermId" => $data['pos_no'],
                    "PayLs" =>  $data['out_trade_no'],
                    "TranId" => '203001',
                ]
            ];


            $base = base::getInstance();
            $ret  = $base->params($params)->build('qr_submit', $base::QR_URL);

            if (isset($ret['RespCode']) && !empty($ret['RespCode'])) {
                if ($ret['RespCode'] == '000000') {
                    return [
                        'status' => 1,
                        'message' => '成功',
                        'data' => [
                            'codeUrl' => $ret['QrCode']
                        ]
                    ];
                } else {
                    $message = '失败了';
                    if (isset($ret['RespMsg'])) {
                        $message = $ret['RespMsg'];
                    }
                    return [
                        'status' => 2,
                        'message' => $message
                    ];
                }
            }
            return [
                'status' => 2,
                'message' => '接口异常'
            ];
        } catch (\Exception $ex) {
            return [
                'status' => 3,
                'message' => $ex->getMessage().' | '. $ex->getLine(),
            ];
        }
    }



}
